<template>
	<view class="chat-container">
		<!-- 聊天消息列表 -->
		<scroll-view class="message-list" scroll-y :scroll-top="scrollTop" @tap="onMessageListTap">
			<view v-for="(item, index) in messageList" :key="index" class="message-item"
				:class="item.type === 'passenger' ? 'passenger' : 'driver'">
				<view class="avatar">
					<image :src="item.type === 'passenger' ? passengerUrl : driverUrl"
						mode="aspectFill"></image>
				</view>
				<view class="message-content">
					<text class="message-text">{{ item.content }}</text>
				</view>
			</view>
		</scroll-view>

		<!-- 输入框区域 -->
		<view class="input-area" :style="{ bottom: keyboardHeight + 'px' }">
			<input type="text" v-model="inputMessage" placeholder="请输入消息" class="message-input" 
				@focus="onInputFocus" @blur="onInputBlur" />
			<button @tap="sendMessage" class="send-btn">发送</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				passengerId:"",
				passengerUrl:"https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/passenger.jpg",
				driverUrl:"https://jf2411-dd.oss-cn-hangzhou.aliyuncs.com/driver.jpg",
				messageList: [
				],
				inputMessage: '',
				scrollTop: 0,
				socket: null,
				keyboardHeight: 0
			}
		},
		onLoad(options) {
			if (options.passengerId) {
			        this.passengerId = options.passengerId;
			        console.log('乘客ID:', this.passengerId);
			    }
			// 页面加载完成实现调用websocket
			this.initWebSocket();
		},
		onUnload() {
			// 组件卸载时关闭连接
			if (this.socket) {
				this.socket.close();
			}
		},
		methods: {
			initWebSocket() {
				//获取司机的token
				const token = uni.getStorageSync('token');
				//获取司机信息
				const driver = uni.getStorageSync('userInfo');
				this.driverUrl = driver.avatar;
				console.log(driver.driverId)
				console.log(token)
				this.socket = uni.connectSocket({
					url: 'ws://127.0.0.1:8005/chat',
					header: {
						'Cookie': 'token=' + token, //redis中存放用户信息的key值
						'sender_type': 'driver', //发送方类型
						'conversationId': 'passenger_' + this.passengerId + '-driver_'+  driver.driverId, //历史记录id
					},
					success: () => console.log('连接建立中...')
				});

				this.socket.onOpen(() => {
					console.log('WebSocket连接已打开');
				});

				this.socket.onMessage(res => {
					console.log('收到消息:', res.data);
					const msg = JSON.parse(res.data)
					console.log("res.data.senderType:",msg.senderType)
					console.log("res.data.content:",msg.content)
					this.messageList.push({
						type: msg.senderType,
						content: msg.content // 假设后端返回JSON格式
					});
					this.scrollToBottom();
				});

				this.socket.onError(err => {
					console.error('WebSocket错误:', err);
				});

				this.socket.onClose(() => {
					console.log('WebSocket连接已关闭');
				});
			},
			sendMessage() {
				if (!this.inputMessage.trim()) return;

				// 添加乘客新消息
				this.messageList.push({
					type: 'driver',
					content: this.inputMessage
				});
				//发送消息
				if (this.socket) {
					const message = {
						toUserId:  this.passengerId,
						content: this.inputMessage
					};
					console.log(message)
					this.socket.send({
						data: JSON.stringify(message),
						success: () => {
							console.log('消息发送成功');
							this.inputMessage = '';
							this.scrollToBottom();
						},
						fail: (err) => {
							console.error('消息发送失败:', err);
						}
					});
				}else {
					console.error('WebSocket连接未建立');
				}
			},
			scrollToBottom() {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.selectAll('.message-item').boundingClientRect(data => {
						if (data && data.length > 0) {
							// 计算所有消息项的总高度
							const totalHeight = data.reduce((sum, item) => sum + item.height, 0);
							// 设置滚动位置为总高度
							this.scrollTop = totalHeight;
						}
					}).exec();
				});
			},
			onInputFocus(e) {
				// 获取键盘高度
				uni.onKeyboardHeightChange(res => {
					this.keyboardHeight = res.height;
					this.scrollToBottom();
				});
			},
			onInputBlur() {
				this.keyboardHeight = 0;
			},
			onMessageListTap() {
				// 点击消息列表时收起键盘
				uni.hideKeyboard();
			}
		}
	}
</script>

<style>
	.chat-container {
		width: 100%;
		height: 100vh; /* 全屏高度 */
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
		position: relative;
	}
	
	.message-list {
		flex: 1; /* 自动撑满上部空间 */
		overflow-y: auto;
		padding: 20rpx;
		background-color: #fff;
		padding-bottom: 120rpx; /* 为输入框留出空间 */
	}
	

	.message-item {
		display: flex;
		margin-bottom: 30rpx;
	}

	.message-item.driver {
		flex-direction: row-reverse;
	}

	.message-item.passenger {
		flex-direction: row;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		margin: 0 20rpx;
	}

	.avatar image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}

	.message-content {
		max-width: 60%;
		background-color: #fff;
		padding: 20rpx;
		border-radius: 10rpx;
	}

	.passenger .message-content {
		background-color: #007AFF;
	}

	.passenger .message-text {
		color: #fff;
	}

	.driver .message-content {
		background-color: #fff;
	}

	.message-text {
		font-size: 28rpx;
		line-height: 1.5;
	}

	.input-area {
		display: flex;
		padding: 20rpx;
		background-color: #fff;
		border-top: 1rpx solid #eee;
		position: fixed;
		left: 0;
		right: 0;
		z-index: 999;
		transition: bottom 0.3s;
	}

	.message-input {
		flex: 1;
		height: 80rpx;
		background-color: #f5f5f5;
		border-radius: 40rpx;
		padding: 0 30rpx;
		margin-right: 20rpx;
	}

	.send-btn {
		width: 120rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background-color: #007AFF;
		color: #fff;
		border-radius: 40rpx;
		font-size: 28rpx;
	}
</style>